<template>
  <el-dialog :title="title" v-model="model" width="800px" append-to-body>
    <el-form ref="areaRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="小区" prop="communityId">
        <community-select v-model="form.communityId" />
      </el-form-item>
      <el-form-item label="区域名称" prop="region">
        <el-input v-model="form.region" placeholder="请输入区域名称" />
      </el-form-item>
      <el-form-item
        v-for="(address, index) in addressList"
        :key="index"
        :label="index === 0 ? '地址' : ''"
        prop="addressList"
      >
        <div class="flex items-center w-full">
          <el-input
            v-model="address.value"
            placeholder="请输入地址"
            class="flex-1"
          />
          <el-button
            v-if="index === addressList.length - 1"
            type="primary"
            link
            class="ml-2"
            @click="handleAddAddress"
          >
            <el-icon><Plus /></el-icon>
          </el-button>
          <el-button
            v-if="addressList.length > 1"
            type="danger"
            link
            class="ml-2"
            @click="handleDeleteAddress(index)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">完 成</el-button>
        <el-button @click="model = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, getCurrentInstance, computed, onMounted } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import CommunitySelect from "@/components/communitySelect/index.vue";
import { saveRegion, updateRegion } from "@/api/realEstateManage.js";

const { proxy } = getCurrentInstance();

const props = defineProps({
  title: {
    type: String,
    default: "新增区域",
  },
  row: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["submit"]);
const model = defineModel({ default: false });
const isEdit = computed(() => !!props.row.id);

const addressList = ref([{ value: "" }]);
const form = ref({
  communityId: undefined,
  region: "",
});

const rules = ref({
  communityId: [{ required: true, message: "请选择小区", trigger: "change" }],
  region: [{ required: true, message: "请输入区域名称", trigger: "blur" }],
  addressList: [
    // 地址length， 并且不为空
    {
      validator: (rule, value, callback) => {
        console.log("[ addressList.value ] >", addressList.value);
        if (addressList.value.every((addr) => addr.value === "")) {
          callback(new Error("请填写地址"));
        }
        callback();
      },
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  if (isEdit.value) {
    form.value = {
      communityId: props.row.communityId,
      region: props.row.region,
    };
    // 如果是编辑，解析smallAddress JSON字符串并填充地址列表
    try {
      const addresses = JSON.parse(props.row.smallAddress || "[]");
      addressList.value = addresses.map((addr) => ({ value: addr }));
      if (addressList.value.length === 0) {
        addressList.value = [{ value: "" }];
      }
    } catch (e) {
      addressList.value = [{ value: "" }];
    }
  }
});

function handleAddAddress() {
  // 判断上一个地址是否填写
  if (addressList.value[addressList.value.length - 1].value === "") {
    proxy.$modal.msgError("请先填写地址");
    return;
  }
  addressList.value.push({ value: "" });
}

function handleDeleteAddress(index) {
  addressList.value.splice(index, 1);
}

function submitForm() {
  proxy.$refs["areaRef"].validate((valid) => {
    if (valid) {
      const params = {
        ...form.value,
        smallAddress: JSON.stringify(
          addressList.value.map((addr) => addr.value)
        ),
      };
      if (isEdit.value) {
        params.id = props.row.id;
      }

      const api = isEdit.value ? updateRegion : saveRegion;
      api(params).then(() => {
        proxy.$modal.msgSuccess(isEdit.value ? "修改成功" : "新增成功");
        model.value = false;
        emit("submit");
      });
    }
  });
}
</script>

<style scoped lang="scss">
.el-form {
  .el-input {
    width: 100%;
  }
}
</style>
